package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.atguigu.lease.common.Exceptions.LeaseException;
import com.atguigu.lease.common.jwtUtils.JwtUtil;
import com.atguigu.lease.common.redis.RedisConstant;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private Client client;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void getCodes(String phone) throws Exception {
        //key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        System.out.println("key = " + key);
        //判断手机号是否在redis中，redis键值同存亡
        Boolean isNUll = redisTemplate.hasKey(key);
        if (isNUll) {
            //有 抛异常
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //没有，生成六位验证码
//        Random random = new Random();
        // 生成100000到999999之间的随机整数
//        int randomNumber = 100000 + random.nextInt(900000);
        //3.生成一个短信验证码(四位的随机数字)
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            Random randoms = new Random();
            int number = randoms.nextInt(10);
            sb.append(number);
        }
        System.out.println("sb = " + sb);

        //发送验证码
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + sb.toString() + "\"}\n");

        //发送之后，存储key（前缀手机号）和验证码
        redisTemplate.opsForValue().set(key, sb.toString(), RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        client.sendSms(smsRequest);
    }

    @Override
    public String login(LoginVo loginVo) {
        System.out.println(loginVo.getPhone());
        //1.判断手机后和验证码是否为null
        if (ObjectUtils.isEmpty(loginVo.getPhone())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        if (ObjectUtils.isEmpty(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //2.验证验证码redis是否存在
        String key= RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone();
        System.out.println("key = " + key);
        Object code = redisTemplate.opsForValue().get(key);
        System.out.println("code = " + code);
        // --没有--过期
        if (ObjectUtils.isEmpty(code)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        //-- 有--是否一样
        if (!code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //3.验证手机号
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(lambdaQueryWrapper);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("佚名"+loginVo.getPhone().substring(7));
            userInfoService.save(userInfo);
        }

        //判断账号是否被禁用
        if (userInfo.getStatus().equals(BaseStatus.DISABLE)){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        return JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
    }
}
